// pages/login/login.js
import { userStore } from '@/stores/userStore.js'
import Notify from '@vant/weapp/notify/notify';
import { getstorage, setstorage } from '@/miniprogram/utils/storage.js'
import { captchaVerify, getPhoneCode, userLoginByphone } from '@/miniprogram/utils/API/user.js'
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { encode, decode, encodePublicKey } from '@/miniprogram/utils/security/security.js'
import { userBehavior } from '@/miniprogram/utils/behaviors/userBehavior'
import { captchaVerifyTencen } from '@/miniprogram/utils/API/user'
let app = getApp()
// var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');
// var captchaVerifyCallback = async function (captchaVerifyParam) {
//    let sendDatas = {}
//    let s = JSON.parse(captchaVerifyParam)
//    sendDatas.sceneId = s.sceneId
//    sendDatas.certifyId = s.certifyId
//    sendDatas.deviceToken = s.deviceToken
//    sendDatas.data = s.data
//    const result = await captchaVerify(sendDatas);
//    let isResklt = result.data.data.body.result.verifyResult
//    const verifyResult = {
//       captchaResult: isResklt,
//       bizResult: isResklt,
//    };
//    return verifyResult;
// };
// var onBizResultCallback = function (bizResult) {
//    if (bizResult === true) {
//       // 业务验证通过后的逻辑，如提示通过
//       this.submitFunction()
//    } else {
//       // 业务验证不通过后的逻辑，如提示不通过
//       wx.showToast({
//          title: '业务验证不通过！',
//          duration: 2000,
//          icon: 'error',
//       });
//    }
// };
// async function customFetch(url, option) {
//    option.url = url;
//    return new Promise((resolve, reject) => {
//       wx.request({
//          ...option,
//          success(res) {
//             resolve(res.data);
//          },
//          fail(res) {
//             reject(new Error(res.toString()));
//          },
//       });
//    });
// }

Page({
   behaviors: [userBehavior],
   captId: 193434285,
   verifySuccess: false,
   data: {
      remberMe: 0,
      loginType: 1,
      loadCaptcha: false,
      pluginProps: {},
      hasUserinfo: false,
      sendData: {},
      Timer: null,
      timeDown: 60,
      disableBtn: true,
      phone: '',
      code: '',
      startTime: false,
      alowSubmit: false,
      shoucheck: false,
      refresh: false,
      captchaVerifyCallback: null,
      userName: '',
      password: '',
      passwordType: 'password',
      passwordicon: 'eye-o',
      logintypeList: [
         { id: 1, title: '手机号登录', notes1: "请输入手机号", notes2: "手机号不正确", notes3: "请检查验证码是否正确！", },
         { id: 2, title: '密码登录', notes1: "请输入用户名", notes2: "请输入密码" },
      ],
   },
   onShow() {

   },
   remberMechceck(e) {
      let status = e.detail
      let { remberMe } = this.data
      if (status) {
         remberMe = 1
      } else {
         remberMe = 0
      }
      this.setData({
         remberMe
      })
   },
   forgetPasswordbtn() {

   },
   logintypeChangetap(e) {
      let { id } = e.currentTarget.dataset
      let { loginType } = this.data
      if (id != loginType) {
         loginType = id
      }
      this.setData({
         loginType
      })
   },
   loginbypassword() {
      this.setData({
         loginType: 1
      })
   },
   onClickIcon(e) {
      let { passwordType, passwordicon } = this.data
      if (passwordType === 'password') {
         passwordType = 'text',
            passwordicon = 'closed-eye'
      } else {
         passwordType = 'password',
            passwordicon = 'eye-o'
      }
      this.setData({
         passwordType,
         passwordicon
      })
   },
   formsubmit(event) {
      let { alowSubmit, logintypeList, sendData, loginType, verifySuccess } = this.data
      wx.getLocalIPAddress({
         success(res) {
            sendData.userIp = res.localip
         }
      })
      if (!alowSubmit) {
         wx.showToast({
            title: logintypeList[0].notes3,
            icon: 'error'
         })
         return;
      }
      this.setData({
         alowSubmit: false,
      });

      if (loginType === 2) {
         this.selectComponent('#captcha').show()
         this.setData({
            sendData
         })
      }
      if (loginType === 1 && verifySuccess) {
         this.submitFunction()
      }
   },
   getCode() {
      let { startTime, interceptTimer, loginType, sendData } = this.data
      interceptTimer = false
      this.setData({
         interceptTimer
      })
      wx.getLocalIPAddress({
         success(res) {
            sendData.userIp = res.localip
         }
      })
      if (loginType === 1 && !startTime) {
         this.selectComponent('#captcha').show()
      }
      this.setData({
         sendData
      })
   },
   async getcodeFunction() {
      let sendData = {}
      let { interceptTimer, phone } = this.data
      sendData.phone = phone
      this.setData({
         startTime: true,
         sendData
      })
      let res = await getPhoneCode(sendData)
      if (res.data.code == 200 && !interceptTimer) {
         this.timerDownFunction()
      }
   },
   userNameOnbulr(e) {
      let userName = e.detail.value
      let { logintypeList } = this.data
      if (!userName) {
         wx.showToast({
            title: logintypeList[1].notes1,
            icon: 'error'
         })
         return;
      }
   },
   passwordOnbulr(e) {
      let { userName, logintypeList } = this.data
      let password = e.detail.value
      if (!password) {
         wx.showToast({
            title: logintypeList[1].notes1,
            icon: 'error'
         })
         return;
      } else {
         if (userName != null && password != null) {
            this.setData({
               alowSubmit: true,
            })
         } else {
            this.setData({
               alowSubmit: false
            })
         }

      }
   },
   phoneOnbulr(e) {
      let phone = e.detail.value
      let { logintypeList } = this.data
      let isPhone = /^1[3456789]\d{9}$/.test(phone)
      if (!phone) {
         wx.showToast({
            title: logintypeList[0].notes1,
            icon: 'error'
         })
         return;
      } else if (!isPhone) {
         wx.showToast({
            title: logintypeList[0].notes2,
            icon: 'error'
         })
         return;
      } else {
         if (isPhone) {
            this.setData({
               disableBtn: false,
               phone: phone,
            })
         } else {
            this.setData({
               disableBtn: true,
               phone: '',
            })
         }
      }
   },
   codeinput(e) {
      let { code } = this.data
      let checkCode = e.detail
      code = checkCode
      let arr = checkCode;
      console.log(arr);
      if (checkCode.length === 6) {
         this.setData({
            code,
            alowSubmit: true
         })
      } else {
         this.setData({
            code,
            alowSubmit: false
         })
      }
   },
   async submitFunction() {
      let { loginType, userName, password, phone, code, remberMe } = this.data
      let sendData = {}
      sendData.salt = "MNhOX2jxbSdrVtOTps9RJY588F"
      if (loginType === 1) {
         sendData.loginacct = phone
         sendData.password = code
         sendData.remberMe = remberMe
      }
      if (loginType === 2) {
         sendData.loginacct = userName
         sendData.password = password
         sendData.remberMe = remberMe
      }
      this.setData({
         sendData
      })
      let res = await userLoginByphone(encodePublicKey(JSON.stringify(sendData)))
      if (res.data.code == 200) {
         Notify({ type: 'success', safeAreaInsetTop: true, selector: '#custom-selector', context: this, message: res.data.msg });
         let token = res.cookies
         token.forEach(item => {
            let s = {}
            s.key = item.split('=')[0];
            s.value = item.split('=')[1].replace("; Path", '')
            setstorage(s.key, s.value)
         })
         setstorage("cookies", token)
         this.updateUserInfo()
         clearInterval(this.data.Timer)
         wx.reLaunch({
            url: '/pages/profile/profile',
         })
      } else {
         Notify({ type: 'danger', safeAreaInsetTop: true, selector: '#custom-selector', context: this, message: res.data.msg });
      }
   },
   timerDownFunction(even) {
      var that = this
      let { disableBtn, timeDown, Timer, startTime } = this.data
      disableBtn = true,
         startTime = true,
         Timer = setInterval(function () {
            timeDown--;
            that.setData({
               timeDown
            })
            if (timeDown <= 0 || !startTime) {
               clearInterval(Timer)
               that.setData({
                  startTime: false,
                  disableBtn: false,
                  timeDown: 60,
               })
            }
         }, 1000)
      that.setData({
         Timer,
         disableBtn,
         startTime,
      })
   },
   onLoad() {
      //aliyuncloud
      // var pluginProps = {
      //    SceneId: '1n8jlhe4',
      //    mode: 'popup',
      //    captchaVerifyCallback: captchaVerifyCallback.bind(this),
      //    onBizResultCallback: onBizResultCallback.bind(this),
      //    slideStyle: {
      //       width: 540,
      //       height: 60,
      //    },
      //    language: 'cn',
      //    region: 'cn',
      // };
      // this.setData({
      //    loadCaptcha: true,
      //    pluginProps,
      // });
   },

   onUnload() {

   },

   handlerVerify: function (ev) {
      let { sendData, verifySuccess } = this.data
      if (ev.detail.ret === 0) {
         sendData.ticket = ev.detail.ticket
         sendData.randstr = ev.detail.randstr
         verifySuccess = true
         this.varifybytent(sendData)
      } else {
         verifySuccess = false,
            this.selectComponent('#captcha').refresh()
      }
      this.setData({
         verifySuccess
      })
   },
   handlerReady: function () {
   },
   handlerClose: function (ev) {
      let { loginType } = this.data
      if (ev && ev.detail.ret && ev.detail.ret === 2) {
         console.log('点击了关闭按钮，验证码弹框准备关闭');
      } else {
         console.log('验证完成，验证码弹框准备关闭');
         if (loginType === 2) {
            this.submitFunction()
         }
         if (loginType === 1) {
            this.getcodeFunction()
         }
      }
   },
   handlerError: function (ev) {
      console.log(ev.detail.errMsg)
   },

   async varifybytent(data) {
      let res = await captchaVerifyTencen(data)
      if (res.data.code === 200) {
         Notify: ({ type: 'success', message: "验证成功" })
         return;
      }
      Notify: ({ type: 'info', message: res.data.msg })
   }
})